<template>
  <div>
    <div v-for="(item, index) in comments" :key="index" style="margin-top: 10px">
      <!-- 评论者头像、昵称和点赞区域 -->
      <div style="height: 20px">
        <div style="float: left;margin-left: 5px">
          <!-- 展示评论者头像 -->
          <t-image 
            shape="circle" 
            style="width: 20px;height: 20px;margin-left: 10px" 
            :src="item.comment.imageurl"
          />
        </div>
        <div style="float: left;margin-left: 10px">
          {{ item.comment.nickname }}
        </div>
        <div style="float: right;margin-right: 10px;color: red">
          <!-- 展示点赞数量 -->
          <span v-if="item.comment.likes > 0" style="font-size:xx-small;">
            {{ item.comment.likes }}
          </span>
          <icon-font 
            v-if="item.liked"
            name="heart-filled"  
            @click="handleLike(item.comment.id)"
            class="liked-icon" 
          />
          <icon-font 
            v-else 
            name="heart" 
            @click="handleLike(item.comment.id)"
          /><br>
        </div>
      </div>
      <!-- 评论内容 -->
      <div style="margin-top: 10px;clear: both;margin-left: 10%">
        {{ item.comment.content }}
      </div>
      <!-- 评论创建时间和地址 -->
      <div style="margin-top: 10px;color: grey;font-size: 10px;margin-left: 10%">
        {{ item.comment.createTime }}
        <span style="margin-left: 10px">来自 {{ item.comment.address }}</span>
      </div>
      <t-divider />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { IconFont } from 'tdesign-icons-vue-next';
import { toRefs } from "vue";

const props = defineProps({
  comments: Array
});

const emit = defineEmits(['add-comment-like']);
const { comments } = toRefs(props);

const handleLike = (cid: number) => {
  const commentItem = comments.value.find((c: any) => c.comment.id === cid);
  if (commentItem) {
    commentItem.liked = !commentItem.liked;
    if (commentItem.liked) {
      commentItem.comment.likes += 1;
      emit('add-comment-like', cid);
    } else {
      commentItem.comment.likes -= 1;
    }
  }
};
</script>

<style scoped>
/* 使用更具体的选择器提高优先级 */
div.liked-icon {
  color: green !important; 
}
</style>